Add a service account based helper library for publishing google calendar events.

Daniel O'Connor 10 years ago
parent
commit
604581cf7e
1 changed files with 68 additions and 0 deletions
  1. 68 0
      lib/google_calendar.rb

+ 68 - 0
lib/google_calendar.rb

@@ -0,0 +1,68 @@
1
+require "google-api-client"
2
+
3
+class GoogleCalendar
4
+
5
+  def initialize(config, logger)
6
+    @config = config
7
+    @key = Google::APIClient::PKCS12.load_key(@config['google']['key_file'], @config['google']['key_secret'])
8
+    @client = Google::APIClient.new(application_name: "Huginn", application_version: "0.0.1")
9
+    @client.retries = 2
10
+    @logger ||= logger
11
+
12
+    @calendar = @client.discovered_api('calendar','v3')
13
+
14
+    @logger.info("Setup")
15
+    @logger.debug @calendar.inspect
16
+  end
17
+
18
+  def auth_as(who)
19
+    @client.authorization = Signet::OAuth2::Client.new({
20
+      token_credential_uri: 'https://accounts.google.com/o/oauth2/token',
21
+      audience:             'https://accounts.google.com/o/oauth2/token',
22
+      scope:                'https://www.googleapis.com/auth/calendar',
23
+      issuer:               @config['google']['service_account_email'],
24
+      signing_key:          @key,
25
+      person:               who # Who are we emulating?
26
+    });
27
+
28
+    @client.authorization.fetch_access_token!
29
+  end
30
+
31
+  # who - String: email of user to add event
32
+  # details - JSON String: see https://developers.google.com/google-apps/calendar/v3/reference/events/insert
33
+  def publish_as(who, details)
34
+    auth_as(who)
35
+
36
+    @logger.info("Attempting to create event for " + who)
37
+    @logger.debug details.to_yaml
38
+
39
+    ret = @client.execute(
40
+      api_method: @calendar.events.insert,
41
+      parameters: {'calendarId' => who, 'sendNotifications' => true},
42
+      body: details,
43
+      headers: {'Content-Type' => 'application/json'}
44
+    )
45
+    @logger.debug ret.to_yaml
46
+    ret
47
+  end
48
+
49
+  def events_as(who, date)
50
+    auth_as(who)
51
+
52
+    date ||= Date.today
53
+
54
+    @logger.info("Attempting to receive events for "+who)
55
+    @logger.debug details.to_yaml
56
+
57
+    ret = @client.execute(
58
+      api_method: @calendar.events.list,
59
+      parameters: {'calendarId' => who, 'sendNotifications' => true},
60
+      body: details,
61
+      headers: {'Content-Type' => 'application/json'}
62
+    )
63
+
64
+    @logger.debug ret.to_yaml
65
+    ret    
66
+  end
67
+
68
+end